const log4js = require('koa-log4');
const logger = log4js.getLogger('services::user');
const bson = require('bson');
const DBRef = bson.DBRef;
const helper = require('mongoskin').helper;
const db = require('../mongodb');

const findAll = async () => {
	return new Promise(function (resolve, reject) {
		db.user.find().toArray(async (err, result) => {
			if (!err) {
				resolve(result);
			} else {
				reject(err);
			}
		});
	});
};

const find = async (q) => {

	let query = q['query'];
	let sort = q['sort'];
	let page = q['page'];

	let pageIndex = page['index'];
	let pageSize = page['size'];
	let skip = (pageIndex - 1) * pageSize;

	//-----------------notice start--------------
	// 处理ObjectId字段
	if (query._id) {
		query._id = helper.toObjectID(query._id)
	}

	//-----------------notice end--------------

	// 查询数量
	let query_count = new Promise((resolve, reject) => {
		db.user.count(query, async (err, result) => {
			if (!err) {
				resolve(result);
			} else {
				reject(err);
			}
		});
	});

	// 查询数据
	let query_data = new Promise((resolve, reject) => {
		db.user.find(query).sort(sort).skip(skip).limit(pageSize).toArray(async (err, result) => {
			if (!err) {
				resolve(result);
			} else {
				reject(err);
			}
		});
	});

	// 构造分页信息
	let buildPageInfo = (pageIndex, pageSize, totalCount) => {

		// let totalPage = (totalCount % pageSize > 0) ? parseInt(totalCount / pageSize) + 1 : Math.floor(totalCount / pageSize);

		// 向上取整
		let totalPage = Math.ceil(totalCount / pageSize);
		let nextPage = (pageIndex == totalPage) ? pageIndex : pageIndex + 1;
		let prePage = (pageIndex > 1) ? pageIndex - 1 : pageIndex;
		let lastResultIndex = pageIndex * pageSize - 1;
		let firstResultIndex = (pageIndex - 1) * pageSize;

		let pageInfo = {
			firstResultIndex: firstResultIndex,
			lastResultIndex: lastResultIndex,
			pageIndex: pageIndex,
			pageSize: pageSize,
			prePage: prePage,
			nextPage: nextPage,
			totalCount: totalCount,
			totalPage: totalPage
		};

		return pageInfo;
	};

	// 构造分页结果
	let buildPage = new Promise((resolve, reject) => {
		Promise.all([query_count, query_data]).then((datas) => {

			let totalCount = datas[0];
			let data = datas[1];

			console.log(data[0]);
			console.log(data[1]);

			let result = {
				pageDatas: data,
				pageuser: buildPageInfo(pageIndex, pageSize, totalCount)
			};

			resolve(result);
		});

	});

	return buildPage;

};

const findById = async (id) => {
	return new Promise(function (resolve, reject) {
		db.user.findOne({_id: helper.toObjectID(id)}, async (err, result) => {
			if (!err) {
				resolve(result);
			} else {
				reject(err);
			}
		});
	});
};

const findByName = async (name) => {
	return new Promise(function (resolve, reject) {
		db.user.findOne({username: name}, async (err, result) => {
			if (!err) {
				resolve(result);
			} else {
				reject(err);
			}
		});
	});
};

const insert = async (user) => {

	user.createdAt = new Date();

	return new Promise((resolve, reject) => {
		db.user.insert(user, async (err, result) => {
			if (!err) {
				resolve(result);
			} else {
				reject(err);
			}
		});
	});
};

const save = async (user) => {
	user.lastModifiedAt = new Date();

	return new Promise((resolve, reject) => {
		db.user.save(user, async (err, result) => {
			if (!err) {
				resolve(result);
			} else {
				reject(err);
			}
		});
	});
};

/**
 *
 * @param update
 * @returns {Promise}
 */
const update = async (query, update) => {
	return new Promise((resolve, reject) => {
		// update({查询字段},{修改部分},function(error,result){ //异步回掉函数 });
		db.user.update(query, update, async (err, result) => {
			if (!err) {
				resolve(result);
			} else {
				reject(err);
			}
		});
	});
};

const findAndModify = async (query, update,) => {
    return new Promise((resolve, reject) => {
        // findAndModify({查询字段},[排序字段],{修改部分},{配置属性},function(error,result){ //异步回掉函数} });
        db.user.findAndModify(query, {}, update, {new: true, upsert: true}, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

const delById = async (id) => {
	return new Promise(function (resolve, reject) {
		db.user.remove({_id: helper.toObjectID(id)}, async (err, result) => {
			if (!err) {
				resolve(result);
			} else {
				reject(err);
			}
		});
	});
};

// 验证用户是否存在
const checkUser = async (query) => {
	return new Promise((resolve, reject) => {
		db.user.findOne(query, async (err, result) => {
			if (!err) {
				resolve(result);
			} else {
				reject(err);
			}
		});
	});
}

exports = module.exports = {
	findAll, findById, findByName, find, insert, save, delById, update, findAndModify, checkUser
};
